package itsm.isperp.module.controller.api.mobile;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.JsonBuilder;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.service.change.ChgChangeService;
import itsm.isperp.module.service.configuration.ConfCiPropertyService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.configuration.ConfCiUseRelationService;
import itsm.isperp.module.service.incident.IcdIncidentService;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * 手机端资产接口控制器
 * 
 * @author zhouhg
 * @date 2014-3-27
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/mobile/configuration")
public class MobileCIController {

	public static final Logger logger = LoggerFactory
			.getLogger(MobileCIController.class);

	/**
	 * 获取资产明细信息
	 * 
	 * @param 资产id
	 * @return
	 */
	@RequestMapping("ciDetail")
	@ResponseBody
	public ResultMessage ciDetail(String id) {
		try {

			ConfCiService confCiService = ContextHolder
					.getSpringBean(ConfCiService.class);

			Map<String, Object> result = confCiService.findOneToMap(id, "id",
					"code", "conf_category_name", "name", "status",
					"use_staff_name", "address", "manufacturer_provider_name",
					"integrator_provider_name", "maintainer_start_date",
					"maintainer_end_date");

			if (result != null && !result.isEmpty()) {

				ConfCiPropertyService confCiPropertyService = ContextHolder
						.getSpringBean(ConfCiPropertyService.class);

				JqGridRequest reqCiProperty = new JqGridRequest();
				reqCiProperty.isPageable(false);
				reqCiProperty.addFilterRule("conf_ci_id",
						JqGridFilterRuleOp.eq, id);
				reqCiProperty.setSelectColumns("property_name",
						"property_value");

				List<Map<String, Object>> list1 = confCiPropertyService
						.findAllDetailByRequest(reqCiProperty).getContent();

				result.put("custom_pi", list1);

				return ResultMessage.success(JsonBuilder.buildNormalBinder()
						.toJson(result));
			} else {
				return ResultMessage.failure("该资产已删除!");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取资产详情失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 获取资产自定义属性
	 * 
	 * @param 资产id
	 * @return
	 */
	@RequestMapping("ciCustomProperties")
	@ResponseBody
	public ResultMessage ciCustomProperties(String id) {
		try {

			ConfCiPropertyService confCiPropertyService = ContextHolder
					.getSpringBean(ConfCiPropertyService.class);

			JqGridRequest request = new JqGridRequest();
			request.isPageable(false);
			request.addFilterRule("conf_ci_id", JqGridFilterRuleOp.eq, id);
			request.setSelectColumns("property_name", "property_value");

			List<Map<String, Object>> list = confCiPropertyService
					.findAllDetailByRequest(request).getContent();
			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取资产详情失败，原因是：" + e.getMessage());
		}

	}

	@RequestMapping("ciUseRelation")
	@ResponseBody
	public ResultMessage ciUseRelation(String relationId) {
		try {
			ConfCiUseRelationService confCiUseRelationService = ContextHolder
					.getSpringBean("confCiUseRelationService");
			JqGridRequest request = new JqGridRequest();
			request.isPageable(false);
			request.addFilterRule("relationId", JqGridFilterRuleOp.eq,
					relationId);

			request.setSelectColumns("id", "ci_id", "code",
					"conf_category_name", "name", "status", "use_staff_name");

			List<Map<String, Object>> list = confCiUseRelationService
					.findAllDetailByRequest(request).getContent();
			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取资产详情失败，原因是：" + e.getMessage());
		}
	}

	/**
	 * 获取资产故障履历
	 * 
	 * @param 资产id
	 * @return
	 */
	@RequestMapping("ciIncidentResume")
	@ResponseBody
	public ResultMessage ciIncidentResume(String id) {
		try {

			IcdIncidentService icdIncidentService = ContextHolder
					.getSpringBean(IcdIncidentService.class);

			List<Map<String, Object>> list = icdIncidentService
					.findCiIncidentDetail(id);
			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取资产故障履历，原因是：" + e.getMessage());
		}

	}

	/**
	 * 获取资产故障履历
	 * 
	 * @param 资产id
	 * @return
	 */
	@RequestMapping("ciChangeResume")
	@ResponseBody
	public ResultMessage ciChangeResume(String id) {
		try {

			ChgChangeService chgChangeServie = ContextHolder
					.getSpringBean(ChgChangeService.class);

			List<Map<String, Object>> list = chgChangeServie
					.findCiChangeDetail(id);
			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取资产故障履历，原因是：" + e.getMessage());
		}

	}

	/**
	 * 资产查询
	 * 
	 * @param keyword
	 *            关键字（编码、分类、名称、使用者）
	 * @param currentPage
	 *            页码
	 * @param size
	 *            加载数量（默认20）
	 * @return
	 */
	@RequestMapping("search")
	@ResponseBody
	public ResultMessage search(String keyword, Integer currentPage,
			Integer size) {

		ConfCiService confCiService = ContextHolder
				.getSpringBean(ConfCiService.class);
		try {
			// to do
			if (size == null || size <= 0) {
				size = 20;
			}

			JqGridRequest request = new JqGridRequest();
			request.setPageable(true);
			request.setRows(size);
			request.setSort("id", Direction.DESC);
			request.setPage(currentPage);

			request.setSelectColumns("id", "code", "conf_category_name",
					"name", "status", "use_staff_name", "asset_code");

			request.setSearchString(" ((a.code like '%" + keyword
					+ "%' ) or(use_staff_name like '%" + keyword
					+ "%' ) or(conf_category_name like '%" + keyword
					+ "%' ) or(a.name like '%" + keyword
					+ "%' )or(asset_code like '%" + keyword + "%' ))");

			List<Map<String, Object>> list = confCiService
					.findAllDetailByRequest(request).getContent();

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("资产搜索失败，原因是：" + e.getMessage());
		}

	}

}
